/* eslint-disable */
// tools
let wx = typeof WXEnvironment === 'object' && WXEnvironment.weexVersion ? WXEnvironment : undefined;
let isH5 = !wx || wx.platform === 'Web';
function isDefined(v) {
  return v !== undefined && v !== null;
}
var nowtime = function () {
  return Date.now() * 1000;
};
var isArray = function (a) {
  return isDefined(a) && a instanceof Array;
};
var forEachArray = function (datas, fn) {
  if (!isArray(datas)) {
    return;
  }
  for (var i = 0, len = datas.length; i < len; i++) {
    var data = datas[i];
    // try {
    if (fn(data, i) === false) {
      break;
    }
    // } catch (error) {
    // }
  }
};

var forEachOwn = function (datas, fn) {
  if (!isDefined(datas)) {
    return;
  }
  for (var key in datas) {
    if (hasOwnProperty(datas, key)) {
      var data = datas[key];
      try {
        if (fn(data, key) === false) {
          break;
        }
      } catch (error) {}
    }
  }
};
var isReadable = function (v) {
  return isDefined(v) && !isEmpty(v);
};
var isEmpty = function (a) {
  if (isDefined(a)) {
    if (hasOwnProperty(a, 'length')) {
      return !a.length;
    }
    if (hasOwnProperty(a, 'size')) {
      return !a.size;
    }
    for (var i in a) {
      if (hasOwnProperty(a, i)) {
        return false;
      }
    }
  }
  return true;
};
var hasOwnProperty = function (object, property) {
  return object && Object.prototype.hasOwnProperty.call(object, property);
};
var forEach = function (datas, fn) {
  if (isArray(datas)) {
    return forEachArray(datas, fn);
  }
  return forEachOwn(datas, fn);
};
var getBaseUrl = function (url) {
  let bundleUrl = new String(weex.config.bundleUrl);
  const isAndroidAssets = bundleUrl.indexOf('file://assets/') >= 0;
  const isIOSAssets = bundleUrl.indexOf('file:///') >= 0 && bundleUrl.indexOf('sign-app') > 0;
  let nativeBase;
  if (isAndroidAssets) {
    nativeBase = 'file://assets/dist/' + url;
  } else if (isIOSAssets) {
    nativeBase = bundleUrl.substring(0, bundleUrl.lastIndexOf('/') + 1) + url;
  } else {
    let host = 'localhost:8081';
    const matches = /\/\/([^\/]+?)\//.exec(bundleUrl);
    if (matches && matches.length >= 2) {
      host = matches[1];
    }
    if (typeof window === 'object') {
      nativeBase = 'http://' + host;
    } else {
      nativeBase = 'http://' + host;
    }
    nativeBase = nativeBase + url;
  }
  return nativeBase;
};

class Metric {
  constructor(data, type) {
    this.d_type = type;
    this.data = data || {};
    this.$metric = {};
    // const ent = isDefined(data.info.timestamp) ? data.info.timestamp : now();
    const ent = data && data.info && data.info.timestamp && data.info.timestamp || nowtime();
    this.ent = ent;
    //此处为设置的userInfo之后的事件产生需关联的 userMapkey 值处理
    // if (setUserInfoTimeStamp !== 0 && setUserInfoTimeStamp <= ent) {
    //     this.userMapIndex = lastUserInfoSetMapKey;
    // }
    // if (setUserInfoTimeStamp !== 0) {
    //     this.userMapIndex = lastUserInfoSetMapKey;
    // }
  }
}

Metric.prototype.info = function (field, defaultVal = '', alisName, unmust = false) {
  const $info = this.data.info;
  if (!isDefined($info)) {
    return this;
  }
  let val = $info[field];
  if (!isDefined(val)) {
    val = defaultVal;
  }
  if (isDefined(alisName)) {
    field = alisName;
  }
  if (!(unmust && val === '')) {
    // extracted.call(this, field, val);
    this.$metric[field] = val;
  }
  return this;
};
function extracted(field, val) {
  this.$metric[field] = val;
}
Metric.prototype.metric = function (field, defaultVal = '', alisName) {
  const $metric = this.data.metric;
  if (!isDefined($metric)) {
    return this;
  }
  let val = $metric[field];
  if (!isDefined(val)) {
    val = isDefined(defaultVal) ? defaultVal : -1;
  }
  if (isDefined(alisName)) {
    field = alisName;
  }
  extracted.call(this, field, val);
  return this;
};
Metric.prototype.build = function (msg) {
  const event = {
    'type': this.d_type,
    'ent': msg && msg.ent ? msg.ent : this.ent,
    'data': {}
  }; //||getFirstUserInfoSetMapKey()
  const unit = this.$metric;
  //有附加值的时候 ，复制给ext属性
  // if (isDefined(this.data.ext)) {
  //     switch (this.d_type) {
  //         // case ACTION:
  //         //     unit.i = isDefined(this.data.ext) ? getXpath(this.data) :'';
  //         //     break;
  //         // case NET:
  //         //     break;
  //         // case ERROR:
  //         case ROUTE:
  //             break;
  //         case PAGE:
  //         case RESOURCE:
  //         case WEBVIEWDATA:
  //         default:
  //             unit.ext = this.data.ext;
  //     }
  // }
  unit.ext = this.data.ext;
  event.data = unit;
  return event;
};

const TIMESTAMP = 'timestamp';
const START_TIME = 'startTime';
const DURATION = 'duration';
const ROUTE = 'routechange';
const ROUTE_DATA = 'data/route';
const URL = 'url';
const REFERRER = 'referrer';
const STATUS = 'status';
const ALIAS = 'alias';
const PATH = 'path';
const ROOT = 'root';
const FULL_URL = 'fullUrl';
const FRAME_WORK = 'framework';
const CUSTOM_IC = 'customIc';
function RouteCleaner() {
  this.route = null;
  this.runingRoute = null;
}
function extendInfo(target, from) {
  if (isDefined(from)) {
    forEach(['url', 'framework', 'version', 'path', 'alias', 'root', 'mode', 'ext', 'pattern', 'fullUrl'], function (e) {
      const val = from[e];
      if (isDefined(val)) {
        target[e] = val;
      }
    });
  }
}
RouteCleaner.prototype.start = function (info) {
  const curTime = nowtime();
  const routeInfo = {};
  routeInfo[START_TIME] = curTime;
  routeInfo[TIMESTAMP] = curTime;
  extendInfo(routeInfo, info);
  routeInfo.referrer = isDefined(this.route) ? this.route.url : '';
  this.runingRoute = routeInfo;
};
RouteCleaner.prototype.end = function (info) {
  const routeInfo = this.runingRoute;
  if (!isDefined(routeInfo)) {
    return;
  }
  const curTime = nowtime();
  routeInfo[DURATION] = curTime - routeInfo[TIMESTAMP];
  routeInfo.status = info && isDefined(info.status) ? info.status : 0;
  extendInfo(routeInfo, info);
  //增加全量地址，去掉了锚点拼接的完整路径
  routeInfo.url.split("//");
  //   routeInfo['fullUrl'] = urlArr[0]+"//"+urlArr[1].replace(/[!#]/g, '').replace(/\/\//g,'/');
  routeData(routeInfo); // 数据$emit
  this.route = routeInfo;
  this.runingRoute = null;
};
var curRoute$1 = '';
function routeData(info) {
  var route = info.url;
  var routeInfo = {
    startTime: nowtime(),
    timestamp: nowtime()
  };
  forEach([START_TIME, TIMESTAMP, DURATION, 'status', 'framework', 'version', 'path', 'alias', 'mode', 'root', 'pattern', 'fullUrl'], function (k) {
    var tar = info[k];
    if (isDefined(tar)) {
      routeInfo[k] = tar;
    }
  });
  routeInfo.url = route;
  routeInfo.referrer = curRoute$1;
  curRoute$1 = route;
  var routeUnit = {
    info: routeInfo
  };
  if (isReadable(info.ext)) {
    routeUnit.ext = info.ext;
  }
  //往sdk端传递路由事件
  let RouteEvent = spaPageRouterData({
    t: ROUTE_DATA,
    p: routeUnit
  });
  console.log(444, RouteEvent);
  if (!isH5) {
    Bonree.reportRouteInfo(stringify({
      ent: RouteEvent.ent,
      v: RouteEvent.data
    }));
  }
}
function spaPageRouterData(data) {
  const baseData = new Metric(data.p, ROUTE);
  baseData.info(URL, '', 'tu').info(REFERRER, '', 'fu').info(DURATION, 0, 'd').info(STATUS, 0, 'sta').info(ALIAS, '', 'al').info(PATH, '', 'pt').info(ROOT, '', 'rt').info(FULL_URL, '', 'pu').info(FRAME_WORK, '', 'fw').info(CUSTOM_IC, false, 'ic');
  return baseData.build();
}
var cleaner = new RouteCleaner();

let curRoute = 0;

// 匹配对应的路径
function getMatchedPattern(matched, path) {
  if (matched.length > 0) {
    const i = matched.length - 1;
    return matched[i].path || path;
  }
  return '[404]';
}
const endIt = function (endNow, status) {
  curRoute -= 1;
  if (endNow === true || curRoute === 0) {
    const info = isDefined(status) ? {
      status: status
    } : null;
    cleaner.end(info);
    curRoute = 0;
  }
};
function install(Vue, opts) {
  if (install.installed) {
    return;
  }
  install.installed = true;
  const vue_version = Vue.version;
  // window['bonreeRUM']['VueVersion'] = vue_version;
  Vue.mixin({
    // beforeCreate: function () {
    //     const router = this.$options.router;
    //         if (isDefined(router)) {
    //             const { base = '', mode = 'hash' } = router.options;
    //         router.beforeEach(function (to, from, next) {
    //                 const { path, matched } = to;
    //                 const pattern = getMatchedPattern(matched, path) || path;
    //                 let status = 0;
    //                 let routeRplaceStr = pattern;
    //                 if(pattern === '[404]'){
    //                     routeRplaceStr = "/404";
    //                     status = 2;
    //                 }
    //                 const location = window.location;
    //                 let fullpath = location.href;
    //                 if (location.search) {
    //                     fullpath = fullpath.replace(/\?[^#?]+/g, '')
    //                 }
    //                 if (mode === 'hash') {           
    //                     fullpath = fullpath.replace(location.hash, '#' + routeRplaceStr)    
    //                 } else if (mode === 'history') {
    //                 fullpath = (base + routeRplaceStr).replace('//', '/')
    //                 fullpath = location.origin + fullpath
    //                 }
    //                 const routeInfo = {
    //                     framework: 'Vue',
    //                     version: vue_version,
    //                     status: status,
    //                     mode: mode,
    //                     url: fullpath,
    //                     path: path,
    //                     pattern: pattern,
    //                     alias: to.name || '',
    //                     root: base || path || '/',
    //                     ext: to.params || {}
    //                 }
    //             cleaner.start(routeInfo)
    //                 next()
    //             })
    //         router.afterEach(function (to, from) {
    //                 // console.log(123,to,from)
    //                 const todo = resolveQueue(from.matched, to.matched)
    //                 const activated = todo.activated  // 当前命中路由
    //                 let components = []
    //                 try {
    //                 components = flatten(activated.map(function (item) {
    //                     return Object.keys(item.components).map(function (key) {
    //                     return item.components[key]
    //                     })
    //                 })).filter(function (comp) {
    //                     return !comp.functional
    //                 })
    //                 } catch (e) {
    //                 components = []
    //                 }

    //                 curRoute = components.length

    //                 if (curRoute === 0) {
    //                 endIt(true,2)
    //                 }
    //             })

    //             if (isDefined(router.onError)) {
    //                 router.onError(function (e) {
    //                 //   error(e);
    //                 endIt(true, 0)
    //                 })
    //             }
    //         } 

    // },
    beforeRouteEnter: function (to, from, next) {
      const {
        path,
        matched
      } = to;
      const pattern = getMatchedPattern(matched, path) || path;
      let status = 0;
      if (pattern === '[404]') {
        status = 2;
      }
      let fullpath = getBaseUrl(path);
      const routeInfo = {
        framework: 'Vue',
        version: vue_version,
        status: status,
        mode: "abstract",
        url: fullpath,
        path: path,
        pattern: pattern,
        alias: to.name || '',
        root: path || '/',
        ext: to.params || {},
        fullUrl: from && from.path || '/'
      };
      cleaner.start(routeInfo);
      next(function (vm) {
        endIt(true, 0);
      });
    }
  });
}
//导出方法
var BonreeVUE = install;

// // 路由数据上报
// function JSreportRouterInfo(){
//     Bonree.reportRouteInfo(info)
// }

let Bonree = {
  startWithAppID: function () {},
  setConfigAddress: function () {},
  setAppVersion: function () {},
  setChannelID: function () {},
  setDeviceID: function () {},
  deviceID: function () {},
  SDKVersion: function () {},
  setUserID: function () {},
  setExtraInfo: function () {},
  setDropFrameTime: function () {},
  useMpaas: function () {},
  useCustomLaunch: function () {},
  recordCustomLaunchEnd: function () {},
  setCustomBusinessHeaders: function () {},
  setSDKRequestHeaders: function () {},
  setCustomPageStart: function () {},
  setCustomPageEnd: function () {},
  setCustomEvent: function () {},
  setCustomEventStart: function () {},
  setCustomEventEnd: function () {},
  setCustomMethodStart: function () {},
  setCustomMethodEnd: function () {},
  setRequestExtraInfo: function () {},
  setCustomNetwork: function () {},
  reportAction: function () {},
  reportView: function () {},
  reportCrash: function () {},
  reportRouteInfo: function () {}
};
function getBonree() {
  if (isDefined(wx) && isDefined(weex)) {
    Bonree = weex.requireModule("Bonree");
  }
}
function BonreeStart() {
  // 更新桥接的函数
  getBonree();
}

export { Bonree, BonreeStart, BonreeVUE };
/* eslint-enable */
